package com.shigui.news.dao.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.opensymphony.xwork2.ActionContext;
import com.shigui.news.dao.BaseDao;
import com.shigui.news.dao.UserDao;
import com.shigui.news.model.User;
@Repository("userDao")
public class UserDaoImpl extends BaseDao implements UserDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	
	@Override
	public User selectById(Integer id) {
		
//		Query query = HibernateUtil.currentSession()
//				.createQuery("from User where id := id");
//		
//		query.setInteger("id", id);
//		
		Query query = getSession().createQuery("from User where id=:id");
		
		query.setInteger("id", id);
		
		User user = (User) query.uniqueResult();
		if(id == user.getId()){
			
			return user;
		}
		
		
		return null;
	}

	@Override
	public List<User> select() {
		
		return null;
	}
   @Transactional
	@Override
	public void insert(User user) {
//		Transaction transaction = getSession().beginTransaction();
		getSession().save(user);
//		transaction.commit();
	}
   @Transactional
	@Override
	public void update(User user) {
		
		getSession().update(user);
	}
   @Transactional
	@Override
	public void delete(User user) {
		
		getSession().delete(user);
	}
	
	public User findByPersistCode(String persistCode){
		Query query = getSession().createQuery("from User where persistCode=:persistCode");
		query.setString("persistCode", persistCode);
		
		return (User) query.uniqueResult();
	}

	@Override
	public User findByUsername(String username) {
		Query query = getSession().createQuery("from User where username=:username");
		
		query.setString("username", username);
		
		
		return (User) query.uniqueResult();
	}

	@Override
	public User findByUser(String username, String password) {

		User user = findByUsername(username);
		
		if(user != null && user.getCipherPassword().equals(password)){
			return user;
		}
		return null;
	}

	@Override
	public void logout() {
		// TODO Auto-generated method stub
		
		ActionContext.getContext().getSession().clear();
	}
	

}
